package com.agileai.miscdp.hotweb.ui.actions.pickfill;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.pickfill.PickFillFuncModel;
import com.agileai.miscdp.hotweb.ui.actions.BaseInitGridAction;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PFMBasicConfigPage;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PickFillModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.pickfill.PickFillModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;
/**
 * 初始化表中功能模型数据
 */
public class PFMInitGridAction extends BaseInitGridAction{
	private PFMBasicConfigPage qBasicConfigPage;
	public PFMInitGridAction() {
	}
	public void setContributor(PickFillModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (PickFillModelEditor)editorPart;
		Shell shell = modelEditor.getSite().getShell();
		
		this.qBasicConfigPage = ((PickFillModelEditor)modelEditor).getBasicConfigPage();

		String funcSubPkg = qBasicConfigPage.getFuncSubPkgText().getText();
		if (StringUtils.isBlank(funcSubPkg)){
			DialogUtil.showInfoMessage("目录编码不能为空！");
			return;
		}
		String listSql = qBasicConfigPage.getListSqlText().getText();
		if (StringUtils.isBlank(listSql)){
			DialogUtil.showInfoMessage("列表Sql不能为空！");
			return;
		}
    	String codeFieldValue = qBasicConfigPage.getCodeFieldText().getText();
    	if (StringUtil.isNullOrEmpty(codeFieldValue)){
    		String codeFieldCheckNullMsg = MiscdpUtil.getIniReader().getValue("PickFillModelEditor","CodeFieldCheckNullMsg");
    		DialogUtil.showInfoMessage(codeFieldCheckNullMsg);
    		return;
    	}
		boolean doInitGrid = MessageDialog.openConfirm(shell,"消息提示","自动填写可能会覆盖已有内容，是否继续!");
		if (!doInitGrid){
			return;
		}
		
        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doRun(monitor);
				} catch (Exception e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
        };
        try {
			progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
					runnable,ResourcesPlugin.getWorkspace().getRoot());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings({"unchecked" })
	public void doRun(IProgressMonitor monitor) {
		monitor.beginTask("init grid values....", 1000);
		monitor.subTask("init basic values....");
		monitor.worked(50);
		
		((PickFillModelEditor)modelEditor).buildFuncModel();
		PickFillFuncModel funcModel = ((PickFillModelEditor)modelEditor).getFuncModel();
		try {
			String funcSubPkg = qBasicConfigPage.getFuncSubPkgText().getText();
			funcModel.setFuncSubPkg(funcSubPkg);
	    	
	    	String sqlMapFile = qBasicConfigPage.getSqlMapFileText().getText();
			File tempSqlMapFile = new File(sqlMapFile);
	    	
	    	String namepPrefix = tempSqlMapFile.getName().substring(0,tempSqlMapFile.getName().lastIndexOf("."));
			funcModel.setListJspName(funcSubPkg +"/"+namepPrefix+"List.jsp");
			String serviceIdTemp = namepPrefix+"Service";
			funcModel.setServiceId(StringUtil.lowerFirst(serviceIdTemp));

			String funcName = funcModel.getFuncName();
			funcModel.setListTitle(funcName);

			String projectName = funcModel.getProjectName();
			ProjectConfig projectConfig = new ProjectConfig();
			String configFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
			projectConfig.setConfigFile(configFile);
			projectConfig.initConfig();
			String mainPkg = projectConfig.getMainPkg();
			funcModel.setImplClassName(mainPkg+".bizmoduler."+funcSubPkg+"."+namepPrefix+"Impl");
			funcModel.setInterfaceName(mainPkg+".bizmoduler."+funcSubPkg+"."+namepPrefix);
			
			SqlBuilder sqlBuilder = new SqlBuilder();
            String listSql = funcModel.getListSql();

        	int lastWhereIndex = listSql.toLowerCase().indexOf("where");
        	if (lastWhereIndex > 0){
        		String lashWhere = listSql.substring(lastWhereIndex,listSql.length());
				List<String> params = MiscdpUtil.getParams(lashWhere);
    			PickFillFuncModel.initPageParameters(params, funcModel.getPageParameters());
        	}
			
			funcModel.setExportCsv(true);
			funcModel.setExportXls(true);
			funcModel.setSortAble(true);
			funcModel.setPagination(true);

			monitor.subTask("init list grid values....");
			monitor.worked(300);
			
			String[] columns = sqlBuilder.parseFields(listSql);
			PickFillFuncModel.initListTableColumns(columns, funcModel.getListTableColumns());
			
			monitor.subTask("init form grid values....");
			monitor.worked(800);
		} catch (Exception e) {
			e.printStackTrace();
		}
		((PickFillModelEditor)modelEditor).setFuncModel(funcModel);
		modelEditor.initValues();
		
		monitor.subTask("refresh viewer....");
		monitor.worked(900);
		
		TableViewer paramTableViewer = ((PickFillModelEditor)modelEditor).getListJspCfgPage().getPageParamTableViewer();
		paramTableViewer.setInput(funcModel.getPageParameters());
		paramTableViewer.refresh();
		
		TableViewer columnTableViewer = ((PickFillModelEditor)modelEditor).getListJspCfgPage().getColumnTableViewer();
		columnTableViewer.setInput(funcModel.getListTableColumns());
		columnTableViewer.refresh();
		
		modelEditor.setModified(true);
		modelEditor.fireDirty();
		
		return;
	}
}
